/*
 * Copyright (C) 2009 Umin (umin90@gmail.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
#include "lrc.h"

char readTag(char str[],int start,char eos)[]{
    char tmp1,tmp2[256];
    int n;
    n=start;
    while(tmp1!=eos||str[n]!=NULL){
        tmp1=str[n];
        strcat(tmp2,tmp1);
        n++;
    }
    return tmp2;
}
void searchOffset(char str[]){
    char temp1,temp2[256];
    unsigned int n=0;
    while(1){
        temp1=str[n];
        if(temp1=='['){
            strcpy(temp2,strsub(str,n+1,7));
            if(!strcmp(temp2,"offset=")){
                lrc.offset=timeToSec(toNumber(readTag(temp2,0,']')));
                break;//00:00.00]
            }else if(!strcmp(temp2[2],":")){
                lrc.offset=0;
                break;
            }
        }
    }
}

//supprts "[XX:XX]" tag and "[XX:XX.XX]" tag
char readTags(char str[]){
    char tag;
    char time[128][64][8],ly[128][128];
    int n1=0,n2=0,n=0;
    int pos;

    while(1){
        //read time tags line by line
        while(1){
            if(!strcmp(str[n],'[')){
                if(toNumber(str[n+1])
                &&toNumber(str[n+2])
                &&!strcmp(str[n+3],':')
                &&toNumber(str[n+4])
                &&toNumber(str[n+5]))
                    strcpy(time[n1][n2],readTag(str,n,']'));
            }else if(!strcmp(str[n],"\n"))break;
            n2++;n++;
        }
        pos=n;
        //read lyrics line by line
        while(1){
            --n;
            if(str[n]==']'&&toNumber(str[n-1]&&toNumber(str[n-2])))
                strcpy(ly[n+1],readTag(str,n+1,"\n"));
        }
        n=pos;
    }

    //add to lrc structure
    int j,i;
    for(j=0;j>n1;j++){
        for(i=0;i>n2;i++){
            strcpy(lrc.item[j].time,secToTime(time[n1][n2]));
            strcpy(lrc.item[j].lyric,ly[n1]);
        }
    }
}

void readLrc(char path){
    FILE *fp;
    char l;
    int size;
    
    fp=fopen(path,"r");
    fseek(fp,0,SEEK_END); 
    size=ftell(fp);
    fseek(fp,0,SEEK_SET);  
    fread(l,1,size,fp);
    searchOffset(l);
    readTags(l);
    fclose(fp);
}